using System.Web;
using System.Web.Routing;
using System.Web.SessionState;
using FubuMVC.Core.Behaviors;
using FubuMVC.Core.Config;
using Microsoft.Practices.ServiceLocation;

namespace FubuMVC.Core.Runtime
{
    public class FubuRouteHandler : IRouteHandler
    {
        private readonly UrlAction _urlAction;
        private readonly IServiceLocator _locator;

        public FubuRouteHandler(UrlAction urlAction, IServiceLocator locator)
        {
            _urlAction = urlAction;
            _locator = locator;
        }

        public IHttpHandler GetHttpHandler(RequestContext requestContext)
        {
            var handler = _locator.GetInstance<IFubuHttpHandler>(_urlAction.UniqueId.ToString());
            handler.CurrentRequestContext = requestContext;
            return handler;
        }
    }

    public interface IFubuHttpHandler : IHttpHandler
    {
        RequestContext CurrentRequestContext { get; set; }
    }

    public class FubuHttpHandler : IFubuHttpHandler, IRequiresSessionState
    {
        private readonly UrlAction _action;
        private readonly IActionBehavior _behavior;
        private readonly ICurrentAction _currentAction;
        private readonly IRequestDictionaryHandler _requestDictionaryHandler;

        public FubuHttpHandler(UrlAction action, IActionBehavior behavior, ICurrentAction currentAction, IRequestDictionaryHandler requestDictionaryHandler)
        {
            _action = action;
            _behavior = behavior;
            _currentAction = currentAction;
            _requestDictionaryHandler = requestDictionaryHandler;
        }

        public void ProcessRequest(HttpContext context)
        {
            _currentAction.Current = _action;
            _currentAction.CurrentRequest = _requestDictionaryHandler.GetDictionary(CurrentRequestContext);

            _behavior.Invoke();
        }

        public bool IsReusable { get { return false; } }
        public RequestContext CurrentRequestContext { get; set; }
    }
}